import axios from 'axios'
import { ElMessage } from 'element-plus'

const http = axios.create({
  baseURL: import.meta.env?.VITE_API_BASE || '/api',
  timeout: 15000,
})

http.interceptors.response.use(
  (resp) => {
    const d = resp.data
    if (d && Object.prototype.hasOwnProperty.call(d, 'code')) {
      if (d.code === 0) {
        return d.data
      }
      ElMessage.error(d.message || '请求失败')
      return Promise.reject(new Error(d.message || '请求失败'))
    }
    return resp.data
  },
  (error) => {
    const resp = error?.response
    const d = resp?.data
    if (d && Object.prototype.hasOwnProperty.call(d, 'code')) {
      ElMessage.error(d.message || '请求失败')
      return Promise.reject(new Error(d.message || '请求失败'))
    }
    ElMessage.error(error?.message || '网络错误')
    return Promise.reject(error)
  }
)

export default http